package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Override
    public void add(AddressBook addressBook) {
        long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        //默认设置成非默认地址
        if (addressBook.getIsDefault() == null) {
            addressBook.setIsDefault(0);
        }
        addressBookMapper.insert(addressBook);
    }

    @Override
    public List<AddressBook> list() {
        long userId = BaseContext.getCurrentId();

        List<AddressBook> addressBooks = addressBookMapper.list(userId);
        return addressBooks;
    }

    @Override
    public void setDefault(long id) {
        //获取userId
        long userId = BaseContext.getCurrentId();
        //把此用户的所有地址都改为非默认
        addressBookMapper.updateStatusByUserId(userId);
        //接下来，再设置默认地址
        AddressBook addressBook = new AddressBook();
        addressBook.setId((long)id);
        addressBook.setIsDefault(1);
        addressBookMapper.update(addressBook);
    }

    @Override
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    @Override
    public AddressBook get(long id) {
        return addressBookMapper.get(id);
    }

    @Override
    public void deleteById(long id) {
        addressBookMapper.deleteById(id);
    }

    @Override
    public AddressBook getDefault() {
        return addressBookMapper.getDefault();
    }
}
